import { IRoute, Tag } from "@/types";
import {
    TagViewAction,
    CHANGE_VISIBLE_TAGS,
    changeVisibleTagsActionCreator,
    CHANGE_ACTIVE_PATH,
} from "./tagViewReducerAction";
import { ThunkAction } from "redux-thunk";
import { RootState } from "../index";
interface TagViewState {
    visibleTags: Tag[];
}
const defaultState: TagViewState = {
    visibleTags: [],
};
export default (state = defaultState, action: TagViewAction) => {
    switch (action.type) {
        case CHANGE_VISIBLE_TAGS:
            return { ...state, visibleTags: action.payload };
        default:
            return state;
    }
};
const deepFindRoute = (routes: IRoute[], path: string): IRoute | undefined => {
    const deepFind = (r: IRoute[]): IRoute | undefined => {
        for (let i = 0; i < r.length; i++) {
            const route = r[i];
            if (route.path === path) {
                return route;
            }
            if (route.children) {
                return deepFind(route.children);
            }
        }
    };
    const route = deepFind(routes);
    return route;
};
export const addTag =
    (path: string): ThunkAction<void, RootState, unknown, TagViewAction> =>
    (dispatch, getState) => {
        const state = getState();
        if (state.tagViews.visibleTags.find(r => r.path === path)) {
            return;
        }
        const route = deepFindRoute(state.menu.routes, path);
        if (route) {
            const visibleTags = [...state.tagViews.visibleTags];
            visibleTags.push({
                name: route.meta?.title,
                path: route.path!,
                isAffix: route.meta?.isAffix,
            });
            dispatch(changeVisibleTagsActionCreator(visibleTags));
        }
    };
export const delTag =
    (tags: Tag[]): ThunkAction<void, RootState, unknown, TagViewAction> =>
    dispatch => {
        dispatch(changeVisibleTagsActionCreator(tags));
    };
export const generateAffixTag =
    (routes: IRoute[]): ThunkAction<void, RootState, unknown, TagViewAction> =>
    dispatch => {
        const tags: Tag[] = [];
        const filterTags = (r: IRoute[]) => {
            r.forEach(o => {
                if (o.meta?.isAffix) {
                    tags.push({
                        name: o.meta?.title,
                        path: o.path!,
                        isAffix: o.meta.isAffix,
                    });
                }
                if (o.children) {
                    filterTags(o.children);
                }
            });
        };
        filterTags(routes);
        dispatch(changeVisibleTagsActionCreator(tags));
    };
